package com.loan.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.oprator.OpratorUtils;
import com.loan.common.utils.DateUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.*;
import com.loan.system.mapper.*;
import com.loan.system.service.OperatorLogService;
import com.loan.system.service.UserService;
import com.loan.system.service.UserVaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shiguang on 2022/8/29 11:09
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final OperatorLogService operatorLogService;

    private final UserVaService userVaService;

    private final UserBankMapper userBankMapper;

    private final SmsSendLogMapper smsSendLogMapper;

    private final PayLogMapper payLogMapper;

    private final ApplyMapper applyMapper;

    private final RepaymentLogMapper repaymentLogMapper;

    @Override
    public UserEntity selectUserById(Long id) {
        return userMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_id", id));
    }

    @Override
    public long getUserCount(String date) {
        return userMapper.selectCount(new QueryWrapper<UserEntity>()
                .between(StringUtils.isNotBlank(date),
                        "create_date", DateUtils.toBeginDateByDay(date), DateUtils.toEndDateByDay(date))
        );
    }


    @Override
    public TableDataInfo<UserEntity> selectPageUserList(UserEntity entity, PageQuery pageQuery) {
        Page<UserEntity> page = userMapper.selectPageUserList(pageQuery.build(), this.buildQueryWrapper(entity));
        return TableDataInfo.build(page);
    }

    /**
     * 修改运营商状态
     */
    @Override
    public void updateUserOperatorStatus() {
        //获取正在爬取运营商的用户
        List<OperatorLog> operatorLogs = operatorLogService.list();
        if (CollectionUtils.isNotEmpty(operatorLogs)) {
            for (OperatorLog entity : operatorLogs) {
                String result = OpratorUtils.getOprator(entity.getPhone());
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (StringUtils.isNoneBlank(jsonObject.getString("status")) && jsonObject.getString("status").equals("-1")) {
                    log.error(jsonObject.getString("message"));
                    entity.setNum(entity.getNum() + 1);
                    if (entity.getNum() >= 3) {
                        entity.setStatus("3");
                        userMapper.updateUserOpratorStatusByUserId(entity.getUserId(),null, "3");
                    }
                    entity.setResult(jsonObject.getString("message"));
                    operatorLogService.updateById(entity);
                } else {
                    entity.setResult(result);
                    entity.setStatus("2");
                    entity.setNum(entity.getNum() + 1);
                    entity.setUpdateTime(new Date());
                    operatorLogService.updateById(entity);
                    //修改用户运营商状态
                    log.info("用户信息:" + entity.getUserId());
                    JSONObject queryInfo = jsonObject.getJSONObject("query_info");
                    userMapper.updateUserOpratorStatusByUserId(entity.getUserId(),queryInfo.getString("tele_company"), "2");
                }
            }
        }
    }

    @Override
    public UserVaEntity getUserVaByApplyId(Long applyId) {
        return userVaService.getUserVaByApplyId(applyId);
    }

    @Override
    public TableDataInfo<Map<String, Object>> selectPageRegisterDataList(String channel, String beginTime, String endTime, Integer pageNum, Integer pageSize) {
        List<Map<String, Object>> list = userMapper.selectPageRegisterDataList(channel, beginTime, endTime, pageNum, pageSize);
        int count = userMapper.count(channel, beginTime, endTime);
        Page<Map<String, Object>> page = new Page<>();
        page.setTotal(count);
        page.setRecords(list);
        return TableDataInfo.build(page);
    }

    @Override
    public List<Map<String, Object>> selectTotalList(String channel, String beginTime, String endTime) {

        return userMapper.selectTotalList(channel,beginTime,endTime);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserById(Long userId) {
        UserEntity userEntity = userMapper.selectById(userId);
        List<ApplyEntity> applyList = applyMapper.selectList(new QueryWrapper<ApplyEntity>().eq("user_id",userId));
        List<Long> ids = applyList.stream().map(entity -> entity.getId()).collect(Collectors.toList());
        //删除用户的银行卡信息
        UserBankEntity userBankEntity = userBankMapper.selectOne(new QueryWrapper<UserBankEntity>().eq("user_id", userId));
        userBankMapper.deleteById(userBankEntity);
        //删除用户短信记录
        QueryWrapper wrapper = new QueryWrapper<SmsSendLogEntity>().like("mobile",userEntity.getUserPhone());
        smsSendLogMapper.delete(wrapper);
        //删除用户打款记录
        if (ids.size() > 0) {
            QueryWrapper wrapper1 = new QueryWrapper<PayLogEntity>().in("apply_id", ids);
            payLogMapper.delete(wrapper1);
        }
        //删除用户还款记录
        QueryWrapper wrapper2 = new QueryWrapper<RepaymentLogEntity>().eq("user_id",userId);
        repaymentLogMapper.delete(wrapper2);
        //删除用户订单
        applyMapper.deleteByIds(ids);
        //删除用户信息
        userMapper.deleteById(userId);
    }

    private Wrapper<UserEntity> buildQueryWrapper(UserEntity userEntity) {
        Map<String, Object> params = userEntity.getParams();
        QueryWrapper<UserEntity> wrapper = Wrappers.query();
        wrapper.eq(ObjectUtil.isNotNull(userEntity.getUserId()), "user_id", userEntity.getUserId())
                .like(StringUtils.isNotBlank(userEntity.getUserPhone()), "user_phone", userEntity.getUserPhone())
                .like(StringUtils.isNotBlank(userEntity.getUserName()), "user_name", userEntity.getUserName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "create_date", params.get("beginTime"), params.get("endTime"))
                .orderByDesc("user_id");
        return wrapper;
    }
}
